import 'dart:convert';
import 'dart:ui';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:chatbot/liaotian.dart';
import 'package:chatbot/yanses.dart';
import 'package:chatbot/shixian_moxing.dart';
import 'package:chatbot/chuangzuo_liebiao_moxing.dart';
import 'package:chatbot/shuju_guanli.dart';
import 'package:chatbot/cunchu_guanli.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:speech_to_text/speech_to_text.dart';
import 'package:speech_to_text/speech_to_text_provider.dart';

class ChuangzaoBiaoqianYemian extends StatefulWidget {
  final SpeechToText shuohua;

  final SpeechToTextProvider shuahuatigong;

  const ChuangzaoBiaoqianYemian(
      {super.key, required this.shuohua, required this.shuahuatigong});

  @override
  _ChuangzaoBiaoqianYemianState createState() =>
      _ChuangzaoBiaoqianYemianState();
}

class _ChuangzaoBiaoqianYemianState extends State<ChuangzaoBiaoqianYemian>
    with
        TickerProviderStateMixin,
        AutomaticKeepAliveClientMixin<ChuangzaoBiaoqianYemian> {
  late TabController biaoqianKongzhi;
  List biaoqian = [];
  List<ChuangzuoTou> chuangzaotouList = [];

  @override
  void initState() {
    super.initState();
    bendiHuoqu();
  }

  void jiexiList(List<dynamic> list, bool isFromNet) {
    debugPrint("local111 list size=${list.length}");
    if (list.isNotEmpty) {
      Chuangzuo? previousCreator;
      int xiabiao = -1;
      chuangzaotouList = [];
      biaoqian = [];
      for (Chuangzuo creator in list) {
        if (previousCreator == null ||
            creator.fenlei != previousCreator.fenlei) {
          xiabiao = xiabiao + 1;
          var biaoqianC = ChuangzuoTou();
          biaoqianC.data = [];
          biaoqianC.title = creator.fenlei;
          biaoqian.add(creator.fenlei);
          chuangzaotouList.add(biaoqianC);
          previousCreator = creator;
        }

        chuangzaotouList[xiabiao].data.add(creator);
      }
      biaoqianKongzhi = TabController(length: biaoqian.length, vsync: this);
    }
    setState(() {});
  }

  wangluohuoqu(bool isUpdate) async {
    int dangqianYe = 1;
    List<Chuangzuo> chuangzaoList = [];
    bool isLastPage = false;
    int totals = 0;
    while (!isLastPage) {
      ChuangzuoLiebiao creatorListModel =
          await QingQiuGuanLi.instance.huoquCHuangzuo(dangqianYe);
      if (creatorListModel.shuju.list.isNotEmpty) {
        dangqianYe += 1;
        totals = creatorListModel.shuju.total;
        chuangzaoList.addAll(creatorListModel.shuju.list);
        isLastPage = creatorListModel.shuju.isLastPage;
      }
    }
    if (isUpdate) {
      jiexiList(chuangzaoList, true);
    }

    if (totals == chuangzaoList.length) {
      debugPrint("save to local2");
      String jsonString = json.encode(chuangzaoList);
      CunChuGuanLi.cunChuangzuoJson(jsonString);
    }
  }

  bendiHuoqu() {
    String? chuangxaoJson = CunChuGuanLi.huoquChuangzuoJson();
    if (chuangxaoJson != "") {
      List mapList = json.decode(chuangxaoJson);

      List<Chuangzuo> creatorList = [];
      for (Map<String, dynamic> map in mapList) {
        creatorList.add(Chuangzuo.fromMap(map));
      }

      jiexiList(creatorList, false);
      wangluohuoqu(false);
    } else {
      wangluohuoqu(true);
    }
  }

  isResponseSuccess(Map response) {
    return response.containsKey('code') && response['code'] == 200;
  }

  @override
  Widget build(BuildContext context) {
    return biaoqian.isEmpty
        ? Scaffold(
            backgroundColor: Yanse.shense,
            body: Center(
              child: CupertinoActivityIndicator(
                  radius: 10.0, color: Yanse.jibenYanse),
            ),
          )
        : Scaffold(
            backgroundColor: Yanse.qianse,
            appBar: PreferredSize(
                preferredSize: Size.fromHeight(30.0),
                child: SafeArea(
                    child: Center(
                  child: TabBar(
                    isScrollable: true,
                    unselectedLabelColor: Color(0xff848691),
                    labelStyle: TextStyle(
                        color: Yanse.jibenYanse,
                        fontSize: 14,
                        fontWeight: FontWeight.w600),
                    unselectedLabelStyle: const TextStyle(
                        fontSize: 14, fontWeight: FontWeight.w600),
                    dividerColor: Yanse.shense,
                    indicatorColor: Yanse.jibenYanse,
                    controller: biaoqianKongzhi,
                    tabs:
                        biaoqian.map((e) => Tab(text: e, height: 30)).toList(),
                  ),
                ))),
            body: TabBarView(
              //构建
              controller: biaoqianKongzhi,
              children: biaoqian.map((e) {
                return ChuangzaoYemian(
                    chuangzaoTouList: chuangzaotouList,
                    biaoti: e,
                    shuoahua: widget.shuohua,
                    shuohuaTigong: widget.shuahuatigong);
              }).toList(),
            ),
          );
  }

  @override
  void dispose() {
    // 释放资源
    biaoqianKongzhi.dispose();
    super.dispose();
  }

  @override
  bool get wantKeepAlive => true;
}

class ChuangzaoYemian extends StatefulWidget {
  final SpeechToText shuoahua;
  final String biaoti;
  final SpeechToTextProvider shuohuaTigong;
  final List<ChuangzuoTou> chuangzaoTouList;

  const ChuangzaoYemian(
      {super.key,
      required this.chuangzaoTouList,
      required this.biaoti,
      required this.shuoahua,
      required this.shuohuaTigong});

  @override
  State<StatefulWidget> createState() {
    return CHuangzuoState(chouangzuoTOuList: chuangzaoTouList, biaoti: biaoti);
  }
}

class CHuangzuoState extends State<ChuangzaoYemian> {
  final String biaoti;
  final List<ChuangzuoTou> chouangzuoTOuList;
  List<Chuangzuo> chuoangzuoList = [];

  CHuangzuoState({required this.chouangzuoTOuList, required this.biaoti});

  @override
  void initState() {
    super.initState();
    setState(() {
      for (ChuangzuoTou section in chouangzuoTOuList) {
        if (section.title == biaoti) {
          chuoangzuoList.addAll(section.data);
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Yanse.shense,
      body: ListView.builder(
          itemCount: chuoangzuoList.length ~/ 2 + chuoangzuoList.length % 2,
          itemBuilder: (BuildContext context, int index) {
            return Row(
              children: [
                ChuangzuoTi(chuoangzuoList[index * 2], widget.shuoahua,
                    widget.shuohuaTigong),
                chuoangzuoList.length > (index * 2 + 1)
                    ? ChuangzuoTi(chuoangzuoList[index * 2 + 1],
                        widget.shuoahua, widget.shuohuaTigong)
                    : Container()
              ],
            );
          }),
    );
  }
}

class ChuangzuoTi extends StatelessWidget {
  final SpeechToTextProvider shuohuaTigong;
  final SpeechToText shuohua;
  final Chuangzuo chuanguzo;

  const ChuangzuoTi(this.chuanguzo, this.shuohua, this.shuohuaTigong);

  @override
  Widget build(BuildContext context) {
    return xuanxiang(chuanguzo, context);
  }

  Widget xuanxiang(Chuangzuo chuangxuo, BuildContext context) {
    return InkWell(
      highlightColor: Colors.transparent, // 透明色
      splashColor: Colors.transparent, // 透
      onTap: () {
        Navigator.push(context,
            CupertinoPageRoute(builder: (BuildContext context) {
          return LiaotianYemian(
            tishiCi: chuangxuo.tishici,
            jueseMing: chuangxuo.biaoti,
            jueseTishi: chuangxuo.fubiaoti,
            leixing: chuangxuo.type,
            tishiTou: chuangxuo.shili,
            shuoHua: shuohua!,
            kouyuTiGong: shuohuaTigong!,
            chuangZao: chuangxuo,
          );
        }));
      },
      child: Container(
          margin: const EdgeInsets.fromLTRB(12, 12, 0, 0),
          height: (MediaQuery.of(context).size.width - 36) * 1.1 / 2,
          width: (MediaQuery.of(context).size.width - 36) / 2,
          child: Stack(
            children: [
              ClipRRect(
                  borderRadius: BorderRadius.circular(16),
                  child: CachedNetworkImage(
                    imageUrl: chuangxuo.tupian,
                    width: (MediaQuery.of(context).size.width - 36) / 2,
                    height: (MediaQuery.of(context).size.width - 36) * 1.1 / 2,
                    fit: BoxFit.cover,
                    errorWidget: (context, url, error) {
                      // debugPrint(error);
                      return const Icon(Icons.error);
                    },
                  )),
              ClipRRect(
                  borderRadius: BorderRadius.circular(16),
                  child: BackdropFilter(
                      // 背景过滤器
                      filter: ImageFilter.blur(sigmaX: 5.0, sigmaY: 5.0),
                      child: Opacity(
                          opacity: 0.7,
                          child: Container(
                            alignment: Alignment.center,
                            height: double.infinity,
                            width: double.infinity,
                            decoration:
                                BoxDecoration(color: Colors.grey.shade900),
                          )))),
              Padding(
                padding: EdgeInsets.fromLTRB(12, 18, 12, 18),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      chuangxuo.biaoti,
                      style: const TextStyle(
                          color: Colors.white,
                          fontSize: 22,
                          fontWeight: FontWeight.w600),
                    ),
                    Expanded(child: Container()),
                    Text(
                      chuangxuo.fubiaoti,
                      overflow: TextOverflow.ellipsis,
                      maxLines: 2,
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: 14,
                          fontWeight: FontWeight.w500),
                    )
                  ],
                ),
              ),
            ],
          )),
    );
  }
}
